import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { formatDate } from "@angular/common";
import { yDataHandler } from './const';
import { FcsService } from "../../service/fcs.service";

@Component({
  selector: 'app-monitor-chart',
  templateUrl: './monitor-chart.component.html',
  styleUrls: ['./monitor-chart.component.less']
})
export class MonitorChartComponent implements OnChanges {
  @Input() title = ''; // 图表标题
  @Input() groupId: string; // 指标名
  @Input() functionId: string; // 指标名
  @Input() metricName; // 指标维度
  @Input() startTime: number; // 开始时间
  @Input() endTime: number; // 终止时间
  @Input() stepMultiple: number; // 步长/采集周期的倍数，默认1,即步长与采集周期一致
  @Input() period: string; // 函数周期，s: seconds,m: minute,h: hour
  @Input() fix = 0; // 数据精度，默认保留4位小数
  @Input() divide = 1; // 对数据进行单位换算，同除以一个divide
  @Input() colorRGB = ['#69c7f7', '#f8b551']; // 线条颜色
  @Input() lineTitle: Array<string>;
  @Input() function: 'rate' | 'divide' | 'fix';
  @Input() versionName = '';
  isLoading = false;
  noData = false;
  options;

  constructor(private fcsService: FcsService) { }

  ngOnInit() {
    // this.refreshMonitorData();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (!changes) {
      return;
    }
    this.refreshMonitorData();
  }

  refreshMonitorData() {
    this.isLoading = true;
    if (this.groupId == undefined || this.functionId == undefined || this.startTime == undefined || this.endTime == undefined || this.stepMultiple == undefined || this.metricName == undefined || this.versionName == undefined) {
      return;
    }
    this.fcsService.getFunctionMetrics(this.groupId, this.functionId, this.startTime, this.endTime, this.stepMultiple.toString(), this.metricName, this.versionName).subscribe(
      (monitorData) => {
        this.isLoading = false;
        if (!monitorData['points']) {
          monitorData['points'] = [];
        }
        this.noData = monitorData['points'].length < 1;
        //let xData = monitorData['points'].map(item => formatDate(item['Time'], "y-MM-dd HH:mm:ss'", "en-US"));
        let xData = monitorData['points'].map(item => formatDate(item['Time'], "HH:mm:ss'", "en-US") + '\n' + formatDate(item['Time'], "y-MM-dd", "en-US"));
        let yData;
        if (this.metricName === 'memory') {
          yData = monitorData['points'].map(item => item['Data'] / (1024 * 1024));
        } else {
          yData = monitorData['points'].map(item => item['Data']);
        }
        this.options = this.createEchart({
          color: this.colorRGB,
          title: this.lineTitle,
          xData: xData,
          yData: yData
        });
      }, error => {
        this.isLoading = false;
        this.noData = true;
      }
    );
  }

  private createEchart(opt: {
    color: Array<string>,
    title: Array<string>,
    xData: Array<string>,
    yData: Array<number>,
    ySplitNumber?: number,
    max?,
    min?
  }) {
    const option = {
      color: opt.color,
      legend: {
        right: '0',
        top: '0',
        data: [{ name: opt.title[0] }]
      },
      grid: {
        left: '6%',
        right: '4.5%',
        bottom: '3%',
        top: 40,
        containLabel: true
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line',
          lineStyle: { color: '#e6e6e6' },
          animation: false
        },
        formatter: function (params) {
          return '时间：' + formatDate(params[0].name, "y-MM-dd", "en-US") + ' ' + formatDate(params[0].name, "HH:mm:ss'", "en-US") + '<br/>' + opt.title[0] + '：' + params[0].data
        }
      },
      xAxis: {
        type: 'category', //name:'时间',
        boundaryGap: true,
        splitNumber: 10,
        axisLabel: {
          color: '#404040',
          showMinLabel: true,
        },
        axisLine: {
          lineStyle: {
            color: '#e6e6e6'
          }
        },
        data: opt.xData
      },
      yAxis: {
        type: 'value',
        minInterval: 1,
        splitLine: {
          lineStyle: {
            color: '#ededed'
          }
        },
        axisLabel: {
          color: '#404040'
        },
        axisLine: {
          lineStyle: {
            color: '#e6e6e6'
          }
        },
        max: null,
        min: null
      },
      series: []
    };
    if (opt.max) {
      option.yAxis.max = opt.max;
    }
    if (opt.min) {
      option.yAxis.min = opt.min;
    }
    const series = [{
      name: opt.title[0],
      type: 'line',
      symbol: 'none',
      symbolSize: '6',
      color: opt.color[0], //"#00A852"
      hoverAnimation: false,
      data: opt.yData
    }];
    option.series = series;
    return option;
  }
  /* /!**
    * 获取统一的格式化UTC标准时间
    *!/
   getUTCTime(date: Date): string {
     return date.toISOString().split('.')[0] + 'Z';
   }*/
  /**
   * 获取统一的格式化时间：2020-03-14 13:13:49
   * @param {number | string | Date} value
   * @returns {string}
   */
  getTimeformat(value: number | string | Date = new Date()): string {
    return formatDate(value, 'y-MM-dd HH:mm:ss', 'en-US');
  }
}
